package pe.com.sisnic.seguros.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import pe.com.sisnic.seguros.model.ImagenDB;
import pe.com.sisnic.seguros.service.ImagenService;

@PreAuthorize("isAuthenticated()")
@Controller
public class ImagenController {

	@Autowired
	private ImagenService imagenService;
	
//	@RequestMapping(value = "/getFoto/{idCliente}", method = RequestMethod.GET)
//    public void getFoto(final HttpServletResponse response, @PathVariable Integer idCliente) throws IOException {
//		Foto foto = imagenService.getFoto(idCliente);
////		BufferedImage img = ImageIO.read(new ByteArrayInputStream(foto.getContenido()));		
//        try {
//        	Blob blob = new SerialBlob(foto.getContenido());
//			writeFileContentToHttpResponse(blob, response);
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//    }
	
//	 public static void writeFileContentToHttpResponse(final Blob image, final HttpServletResponse response) throws IOException, SQLException {
//	        
//	    	ServletOutputStream out = response.getOutputStream();
//	    	InputStream in = image.getBinaryStream();
//	    	int lenght = (int)image.length();
//	    	int bufferSize = 1024;
//	    	byte[] buffer = new byte[bufferSize];
//
//	    	response.setContentType("image/png");
//	    	while((lenght = in.read(buffer)) != -1) {
//	    		out.write(buffer, 0, lenght);
//	    	}
//	    	in.close();
//	    	out.flush();
//	    }
	 
	 @RequestMapping(value = "/getFoto/{idCliente}", method = RequestMethod.GET)
	 @ResponseBody
	    public byte[] getFoto(@PathVariable Integer idCliente){
			ImagenDB foto = imagenService.getFoto(idCliente);
			if(foto != null){
				return foto.getContenido();
			} else {
				return null;
			}			
	    }
	 
	 @RequestMapping(value = "/getFirma/{idCliente}", method = RequestMethod.GET)
	 @ResponseBody
	    public byte[] getFirma(@PathVariable Integer idCliente){
			ImagenDB firma = imagenService.getFirma(idCliente);
			if(firma != null){
				return firma.getContenido();
			} else {
				return null;
			}
	    }
}
